import os
import subprocess
import sys


def is_homebrew_installed():
    """检查 Homebrew 是否安装"""
    try:
        subprocess.run(['brew', '--version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def install_libreoffice():
    """使用 Homebrew 安装 LibreOffice"""
    try:
        command = ['brew', 'install', '--cask', 'libreoffice']
        subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("LibreOffice installed successfully")
    except subprocess.CalledProcessError as e:
        print(f"[Error] Installation of LibreOffice failed: {e}")
        sys.exit(1)


def is_libreoffice_installed():
    """检查 LibreOffice 是否安装"""
    try:
        subprocess.run(['/Applications/LibreOffice.app/Contents/MacOS/soffice', '--version'], check=True,
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def ensure_libreoffice_installed():
    """确保 LibreOffice 已安装，如果未安装则尝试安装"""
    if not is_libreoffice_installed():
        print("LibreOffice is not installed, trying to install...")
        if not is_homebrew_installed():
            print("[Error] Homebrew is not installed, please install Homebrew manually first")
            sys.exit(1)
        install_libreoffice()


def word_to_pdf(word_file, pdf_file):
    try:
        ensure_libreoffice_installed()  # 确保 LibreOffice 已安装

        # 确保输出目录存在
        os.makedirs(os.path.dirname(pdf_file), exist_ok=True)

        # 使用 LibreOffice 进行转换
        command = ['/Applications/LibreOffice.app/Contents/MacOS/soffice', '--headless', '--convert-to', 'pdf',
                   word_file,
                   '--outdir', os.path.dirname(pdf_file)]
        subprocess.run(command, check=True)
        print(f"Successfully converted '{word_file}' to '{pdf_file}'")
    except subprocess.CalledProcessError as e:
        print(f"[Error] Conversion failed: {e}")
    except Exception as e:
        print(f"[Error] An unexpected error occurred: {e}")


# 示例用法
if __name__ == '__main__':
    word_file = 'word/test_file_wtp1.docx'
    pdf_file = 'PDF/test_file_wtp1.pdf'
    word_to_pdf(word_file, pdf_file)
